const puppeteer = require('puppeteer')
const R = require('ramda')
const {parseJsonp, keysToLower, toFloat} = require('./utils.js')

/*
    STARTDATE: 起息日期
    LISTDATE: 上市日期
    AISSUEVOL: 发行量
    SWAPPRICE: 转股价
    SWAPSDATE: 转股开始日
    SWAPEDATE: 转股结束日
    CREDITRATING: 信用级别
    PARTIESFNAME: 评级机构
    FRSTVALUEDATE: 起息日
    LASTVALUEDATE: 止息日
    MRTYDATE: 到期日
    RATEDES: 利率说明
*/
const fields = [
    'BONDCODE', 'SNAME', 'SWAPSCODE', 'SECURITYSHORTNAME', 'STARTDATE', 'LISTDATE',
    'SWAPPRICE', 'AISSUEVOL', 'SWAPSDATE', 'SWAPEDATE', 'CREDITRATING', 'PARTIESFNAME',
    'FRSTVALUEDATE', 'LASTVALUEDATE', 'MRTYDATE', 'RATEDES'
]

async function detail(page, bond_code) {
    const url = `http://data.eastmoney.com/kzz/detail/${bond_code}.html`
    await page.setViewport({width: 900, height: 1440})

    let info = {}
    page.on('response', resp => {
        //console.log(resp.url())
        if (resp.url().startsWith('http://dcfm.eastmoney.com/')) {
            //返回的格式"jQuery1123048543535627263656_1621419393782({...})"
            resp.text().then(txt => {
                let obj = parseJsonp(txt)
                if (obj instanceof Array && obj.length === 1) {
                    info = R.merge(info, R.pick(fields, obj[0]))
                }
            })
        }
    })

    await page.goto(url)
    //添加在网页中使用的函数
    await page.evaluate(() => {
        window.getOption = node => {
            let echartid = node.getAttribute('_echarts_instance_')
            return echarts.getInstanceById(echartid).getOption()
        }
        let digData = option => option.series.reduce((acc, val) => {
            acc[val.name] = val.data
            return acc
        }, {})
        window.drawPrices = option => {
            let series = digData(option)
            return {
                dates: option.xAxis[0].data,
                ...series
            }
        }
        window.drawRates = option => {
            let series = digData(option)
            return {
                dates: option.xAxis[0].data,
                ...series
            }
        }
    })

    await page.waitForSelector('#chart_1')
    let prices = await page.$eval('#chart_1', node => {
        return window.drawPrices(window.getOption(node))
    })
    
    let rates = await page.$eval('#chart_2', node => {
        return window.drawRates(window.getOption(node))
    })

    let history = []
    if (!R.equals(prices.dates, rates.dates)) {
        console.log('bondcode: ' + bond_code + ' 两个日期数组长度不相等！')
        return 
    }
    for (let i = 0; i < prices.dates.length; i++) {
        history.push({
            date: new Date(prices.dates[i]),
            closeprice: toFloat(prices['收盘价'][i]),
            pureliability: toFloat(prices['纯债价值'][i]),
            swapprice: toFloat(prices['转股价值'][i]),
            swappremium: toFloat(rates['转股溢价率'][i]),
            liabilitypremium: toFloat(rates['纯债溢价率'][i])
        })
    }
    return {convertible: keysToLower(info), history}
}

module.exports = detail
